package com.ychs.listener; /**
 * copyright(c)2021 YYB.ALL rights Reserved
 * <p>
 * 描述:
 *
 * @author 原玉波
 * @version 1.0
 * @date 2021/7/14
 */

import org.apache.log4j.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener()
public class OnlineListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener {

    private Logger logger = Logger.getLogger(this.getClass());

    /**
     * 在线人数
     */
    private int number ;

    // Public constructor is required by servlet spec
    public OnlineListener() {
    }

    // -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------
    public void contextInitialized(ServletContextEvent sce) {
      /* This method is called when the servlet context is
         initialized(when the Web application is deployed). 
         You can initialize servlet context related data here.
      */
    }

    public void contextDestroyed(ServletContextEvent sce) {
      /* This method is invoked when the Servlet Context 
         (the Web application) is undeployed or 
         Application Server shuts down.
      */
    }

    public void sessionCreated(HttpSessionEvent se) {
        logger.info("session.id："+se.getSession().getId());
        /* Session is created. */
        logger.info("客户端上线");
        synchronized ("lock") {
            this.number++;

            se.getSession().getServletContext()
                    .setAttribute("online",number);
        }
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
        logger.info("客户下线");
        synchronized ("lock") {
            this.number--;

            se.getSession().getServletContext()
                    .setAttribute("online",number);
        }
    }

    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------

    public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute 
         is added to a session.
      */
    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attribute
         is replaced in a session.
      */
    }
}
